"""
AI API 路由 - 提供AI相关的API接口
"""
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from pydantic import BaseModel
from typing import List, Optional, Dict
from app.database import get_db
from app.ai.ai_service import ai_service
from app import crud

router = APIRouter(prefix="/ai", tags=["ai"])

# 数据模型定义
class TextAnalyzeRequest(BaseModel):
    """文本分析请求模型"""
    text: str

class TextAnalyzeResponse(BaseModel):
    """文本分析响应模型"""
    keywords: List[str]
    word_count: int
    processed_text: str

class CaseMatchRequest(BaseModel):
    """案例匹配请求模型"""
    query: str
    category: Optional[str] = None
    limit: Optional[int] = 10

class CaseMatchResponse(BaseModel):
    """案例匹配响应模型"""
    case_id: int
    title: str
    similarity_score: float
    category: str

class CaseRecommendationResponse(BaseModel):
    """案例推荐响应模型"""
    case_id: int
    title: str
    similarity_score: float
    category: str

class ProblemInfoResponse(BaseModel):
    """问题信息提取响应模型"""
    keywords: List[str]
    models: List[str]
    fault_indicators: List[str]
    word_count: int

# API端点实现
@router.post("/analyze", response_model=TextAnalyzeResponse)
async def analyze_text(request: TextAnalyzeRequest):
    """
    分析文本内容，提取关键词等信息
    """
    try:
        result = ai_service.analyze_text(request.text)
        return TextAnalyzeResponse(**result)
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"文本分析失败: {str(e)}"
        )

@router.post("/match", response_model=List[CaseMatchResponse])
async def match_cases(request: CaseMatchRequest, db: Session = Depends(get_db)):
    """
    匹配相似案例
    """
    try:
        similar_cases = ai_service.match_similar_cases(
            request.query, 
            db, 
            category=request.category, 
            limit=request.limit
        )
        
        # 转换为响应格式
        response_data = []
        for case, similarity in similar_cases:
            response_data.append(CaseMatchResponse(
                case_id=case["id"],
                title=case["title"],
                similarity_score=round(similarity, 4),
                category=case["category"]
            ))
        
        return response_data
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"案例匹配失败: {str(e)}"
        )

@router.post("/recommend", response_model=List[CaseRecommendationResponse])
async def recommend_cases(issue_description: str, db: Session = Depends(get_db)):
    """
    推荐解决方案案例
    """
    try:
        recommendations = ai_service.get_case_recommendations(issue_description, db)
        
        # 转换为响应格式
        response_data = []
        for rec in recommendations:
            response_data.append(CaseRecommendationResponse(**rec))
        
        return response_data
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"案例推荐失败: {str(e)}"
        )

@router.post("/extract-problem-info", response_model=ProblemInfoResponse)
async def extract_problem_info(description: str):
    """
    从问题描述中提取关键信息
    """
    try:
        result = ai_service.extract_problem_info(description)
        return ProblemInfoResponse(**result)
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"问题信息提取失败: {str(e)}"
        )